﻿using PLC.Base;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLC.Device
{
    /// <summary>
    /// 替代库 https://zhuanlan.zhihu.com/p/594092517
    /// </summary>
    class PLCSmart200Manager : IDeviceReader
    {
        private String ip = "192.168.2.1";
        private int rack = 0;
        private int slot = 1;
        private ushort connectionType = 3;
        private bool isOpen = false;
        private int dn;
        Plc plc = null;

        #region 接口实现
        public bool IsOpen { get => isOpen;  set => isOpen = value; }

        public void Close()
        {
            if (isOpen)
            {
                plc.Close();
                isOpen = false;
            }
        }

        public int Open()
        {
            if (isOpen)
            {
                return 0;
            }
            plc.Open();
            isOpen = true;
            return 0;
        }



       EnvData IDeviceReader.ReadData(DynamicParams dynamic)
        {
            int dn = dynamic.Dn;
            EnvData data = new EnvData();

            data.PresureIn = ReadFloatData(100);
            data.PresureOut = ReadFloatData(105);
            data.Flow = ReadFloatData(dn);
            data.Temperature = ReadFloatData(140);
            data.Speed = ReadFloatData(145);
      
            return data;
        }
        #endregion

        #region 私有函数
        private float ReadFloatData(int address)
        {
            return (float)plc.Read(DataType.DataBlock, 1, address, VarType.Real, 1);
        }
        #endregion
               
        #region 构造函数
        public PLCSmart200Manager(String ip, int rack, int slot, ushort connectionType)
        {
            this.ip = ip;
            this.rack = rack;
            this.slot = slot;
            this.connectionType = connectionType;
            plc = new Plc(CpuType.S71200, ip, (short)rack, (short)slot);
        }

        #endregion



    }
}
